package com.china08.yxyapi.api.manage.tec.teaching.lecture.chooseprepare;

import java.util.List;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.BasicQuery;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.mg.lecture.YxyLecturePrePack;
import com.china08.yxyapi.model.YxyApiPageReqModel;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.util.YxyResUtil;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;

/**
 * 
 * 挑选备课包--区域备课包
 *
 */
@CrossOrigin
@RestController
public class LectureSchAreaChoosePackController extends YxyApiBaseController {

    private final static Logger LOGGER = LoggerFactory.getLogger(LectureSchAreaChoosePackController.class);

    @Autowired
    private MongoTemplate mt;

    @RequestMapping(value = "/api_yw/manage/tec/teaching/lecture/areachooseprepare/sch", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespModel process(HttpServletRequest request, HttpServletResponse response,
            @RequestBody(required = false) ReqModel reqModel) {
        RespModel respModel = new RespModel();
        String schoolId = getProfile(request, response).getSchoolId();
        String userVIP = getProfile(request, response).getResVip();
        String bookContentsId = reqModel.bookContentsId;
        Integer bureauLevel = reqModel.bureauLevel;
        String areaId = reqModel.areaId;
        Assert.isTrue(StringUtils.isNotBlank(bookContentsId), "目录ID为空");
        String keyword = reqModel.keyword;
        Sort sort = new Sort(Direction.DESC, "isHighQualityYx").and(new Sort(Direction.DESC, reqModel.field));
        Pageable pageable = new PageRequest(reqModel.page, reqModel.size, sort);
        LOGGER.info("开始查询子目录===========");
        Long start = System.currentTimeMillis();
        // 查询子目录
        YxyResUtil resUtil = new YxyResUtil();
        List<String> parent = resUtil.findTocByTocParent(bookContentsId);
        int size = parent.size();
        String[] bookContent = parent.toArray(new String[size]);
        LOGGER.info("查询子目录完成共用时:" + (System.currentTimeMillis() - start) + "ms");

        LOGGER.info("========开始查询备课包=========");
        Long startPack = System.currentTimeMillis();

        // 查询条件
        DBObject dbObject = new BasicDBObject();
        dbObject.put("auditStats", 1);
        dbObject.put("status", 1);
        dbObject.put("share", 1);
        BasicDBObject in = new BasicDBObject("$in", bookContent);
        dbObject.put("bookcontentsId", in);
        // 区
        if (bureauLevel == 0) {
            dbObject.put("areaIdDistrict", areaId);
        } // 市
        else if (bureauLevel == 1) {
            dbObject.put("areaIdCity", areaId);
            // 省
        } else {
            dbObject.put("areaIdProvince", areaId);
        }

        if (StringUtils.isNotBlank(keyword)) {
            Pattern queryPattern = Pattern.compile(keyword, Pattern.CASE_INSENSITIVE);
            dbObject.put("packName", queryPattern);
        }
        // 查询条件
        DBObject dbObjectTwo = new BasicDBObject();
        dbObjectTwo.put("auditStats", 1);
        dbObjectTwo.put("status", 1);
        dbObjectTwo.put("share", 1);
        dbObjectTwo.put("bookcontentsId", in);
        // 区
        if (bureauLevel == 0) {
            dbObjectTwo.put("areaIdDistrict", areaId);
        } // 市
        else if (bureauLevel == 1) {
            dbObjectTwo.put("areaIdCity", areaId);
            // 省
        } else {
            dbObjectTwo.put("areaIdProvince", areaId);
        }

        if (StringUtils.isNotBlank(keyword)) {
            Pattern queryPattern = Pattern.compile(keyword, Pattern.CASE_INSENSITIVE);
            dbObjectTwo.put("userNick", queryPattern);
        }

        // 返回字段
        BasicDBObject fieldsObject = new BasicDBObject();
        fieldsObject.put("isHighQualityYx", true);
        fieldsObject.put("isVip", true);
        fieldsObject.put("packName", true);
        fieldsObject.put("id", true);
        fieldsObject.put("userNick", true);
        fieldsObject.put("schoolNick", true);
        fieldsObject.put("createdDate", true);
        fieldsObject.put("resources", true);
        fieldsObject.put("pv", true);
        fieldsObject.put("schoolId", true);
        fieldsObject.put("packSize", true);
        fieldsObject.put("usedCount", true);
        fieldsObject.put("userId", true);
        fieldsObject.put("bookcontentsId", true);
        fieldsObject.put("bookcontentsName", true);
        fieldsObject.put("auditUserName", true);
        fieldsObject.put("phaseId", true);
        fieldsObject.put("phaseName", true);
        fieldsObject.put("subjectId", true);
        fieldsObject.put("subjectName", true);
        fieldsObject.put("versionId", true);
        fieldsObject.put("versionName", true);
        fieldsObject.put("areaIdProvince", true);
        fieldsObject.put("areaIdCity", true);
        fieldsObject.put("areaIdDistrict", true);
        fieldsObject.put("status", true);
        fieldsObject.put("downReason", true);
        fieldsObject.put("status", true);
        fieldsObject.put("ranks", true);
        fieldsObject.put("isView", true);

        Query query = new BasicQuery(dbObject, fieldsObject);

        Query queryTwo = new BasicQuery(dbObjectTwo, fieldsObject);
        // 总数
        long total = 0l;
        total = mt.count(query, YxyLecturePrePack.class);

        // 排序
        query.with(pageable);
        queryTwo.with(pageable);
        // 分页
        query.skip((pageable.getPageNumber()) * pageable.getPageSize()).limit(pageable.getPageSize());
        queryTwo.skip((pageable.getPageNumber()) * pageable.getPageSize()).limit(pageable.getPageSize());
        List<YxyLecturePrePack> list = null;
        list = mt.find(query, YxyLecturePrePack.class);
        if (total == 0l && list == null) {
            total = mt.count(queryTwo, YxyLecturePrePack.class);
            list = mt.find(queryTwo, YxyLecturePrePack.class);
        }

        LOGGER.info("查询备课包完成共用时:" + (System.currentTimeMillis() - startPack) + "ms");

        Assert.isTrue(null != list, "备课包为空");

        Page<YxyLecturePrePack> pageRes = new PageImpl<YxyLecturePrePack>(list, pageable, total);

        respModel.pageRes = pageRes;
        respModel.schoolId = schoolId;
        respModel.userVIP = userVIP;

        return respModel;
    }

    protected static class ReqModel extends YxyApiPageReqModel {

        public String bookContentsId;
        // 采纳字段usedCount 浏览字段pv 时间createdDate
        public String field;

        public String keyword;

        public String areaId;

        public Integer bureauLevel;

    }

    protected static class RespModel extends YxyApiRespModel {

        public Page<YxyLecturePrePack> pageRes;

        public String userVIP;

        public String schoolId;
    }
}
